package cz.data.gateway.admin.listener;

import cz.data.common.rabbitmq.config.RabbitConstant;
import cz.data.common.utils.JsonCommon;
import cz.data.gateway.admin.mapstruct.GatewayRouteMapper;
import cz.data.gateway.admin.service.IGatewayRouteService;
import cz.data.gateway.model.dto.RouteDefinitionDto;
import cz.data.gateway.model.entity.GatewayRoute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitEventListener {

    @Autowired
    IGatewayRouteService gatewayRoutService;
    @Autowired
    GatewayRouteMapper gatewayRouteMapper;

    @RabbitListener(queues = RabbitConstant.TOPIC_GATEWAY_ADMIN_ROUTE)
    public void gatewayRouteEvent(Message message) {
        RouteDefinitionDto routeDefinition = JsonCommon.parseObject(message.getBody(), RouteDefinitionDto.class);
        log.info("网关admin接收到路由变更通知: {}", routeDefinition);
        if (routeDefinition.remove()) {
            gatewayRoutService.delete(routeDefinition.getId());
        } else {
            GatewayRoute route = gatewayRouteMapper.toEntity(routeDefinition);
            gatewayRoutService.upsert(route);
        }
    }
}
